package com.javaweb.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.javaweb.entity.Result;
import com.javaweb.service.RoomService;
import com.javaweb.utils.JwtUtil;
import com.javaweb.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Slf4j
@Component
public class RoomEnterInterceptor implements HandlerInterceptor {

    @Autowired
    private RoomService roomService;

    //目标资源方法运行前执行 返回true则放行 否则不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}", url);

        //2.在config.WebConfig中设置需要拦截和放行的请求url

        //3.解析房间id
        int id;
        try{
            id = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1));
        } catch (Exception e){
            e.printStackTrace();
            log.info("无法解析的房间id");
            Result error = Result.error("UNPARSEABLE_ROOM_ID");
            //手动转换对象 JSON ----> 阿里巴巴fastJSON
            String errorStr = JSONObject.toJSONString(error);
            response.setStatus(404);
            response.getWriter().write(errorStr);
            return false;
        }

        //4.判断房间是否存在
        if (roomService.findById(id) == null) {
            log.info("房间不存在");
            Result error = Result.error("ROOM_NOT_EXISTS");
            //手动转换对象 JSON ----> 阿里巴巴fastJSON
            String errorStr = JSONObject.toJSONString(error);
            response.setStatus(404);
            response.getWriter().write(errorStr);
            return false;
        }

        //5.放行
        log.info("允许进入房间。房间id：{}", id);
        return true;
    }
}
